<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of XmlResponse
 *
 * @author pahhan
 */
class Response_JsonResponse extends Response_Response
{
    /**
     * Encode data to json
     * @param mixed $data
     * @return string
     */
    private function encode($data)
    {
        $out = json_encode($data);

        if( isset($_REQUEST['callback']) )
        {
            $out = sprintf('%s(%s)', $_REQUEST['callback'], $out);
        }
        return $out;
    }

    /**
     * Returns content-type for response
     * @return string
     */
    public function getContentType()
    {
        return 'application/json';
    }

    /**
     * Returns error element
     * @param integer $code
     * @param string $message
     * @return array
     */
    private function getErrorElement($code = 0, $message = NULL)
    {
        return array(
            'code' => $code,
            'message' => $message
        );
    }

    /**
     * Returns error JSON
     * @param integer $code
     * @param string $message
     * @return string
     */
    public function getError($code = 0, $message = null)
    {
        $out = array('error' => $this->getErrorElement($code, $message));
        return $this->encode($out);
    }

    /**
     * Returns update information JSON
     * @param integer $count
     * @param integer $size
     * @param integer $parse_info_id
     * @return string
     */
    public function getUpdateInfo($count, $size, $parse_info_id)
    {
        $out = array('error' => $this->getErrorElement());
        $out['parse_info_id'] = $parse_info_id;
        $out['count'] = $count;
        $out['size'] = $size;
        return $this->encode($out);
    }

    /**
     * Returns sites JSON
     * @param array $sites
     * @return string
     */
    public function getSites(array $sites)
    {
        $out = array('error' => $this->getErrorElement());
        $out['sites'] = $sites;
        return $this->encode($out);
    }

    /**
     * Returns messages XML
     * @param array $messages
     * @return string
     */
    public function getMessages(array $messages)
    {
        $out = array('error' => $this->getErrorElement());
        $out['messages'] = $messages;
        return $this->encode($out);
    }
}

